package wang.hu.bos.web.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import wang.hu.bos.domain.page.PageBean;
import wang.hu.bos.domain.take_delivery.Promotion;

import com.opensymphony.xwork2.ActionContext;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Controller
@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
public class PromotionAction extends BaseAction<Promotion> {
	@Action(value = "promotion_pagedata", results = { @Result(name = "success", type = "json") })
	public String pagedata() {
		PageBean pageBean = WebClient
				.create("http://localhost:8080/bos_management/services/promotionservice/pagedata?page="
						+ page + "&rows=" + rows)
				.type(MediaType.APPLICATION_JSON).get(PageBean.class);
		ActionContext.getContext().getValueStack().push(pageBean);
		return SUCCESS;
	}

	@Action(value = "promotion_detail")
	public String showDetail() throws Exception {
		String realPath = ServletActionContext.getServletContext().getRealPath(
				"/freemarker");
		File htmlFile = new File(realPath + model.getId() + ".html");
		if (!htmlFile.exists()) {
			Configuration configuration = new Configuration(
					Configuration.VERSION_2_3_21);
			configuration.setDirectoryForTemplateLoading(new File(
					ServletActionContext.getServletContext().getRealPath(
							"/WEB-INF/freemark_template")));
			// 获取模板
			Template template = configuration
					.getTemplate("promotion_detail.ftl");
			// 动态数据
			Promotion promotion = WebClient
					.create("http://localhost:8080/bos_management/services/promotionservice/promotion/"
							+ model.getId()).accept(MediaType.APPLICATION_JSON)
					.get(Promotion.class);
			Map<String, Object> hashMap = new HashMap<String, Object>();
			hashMap.put("promotion", promotion);
			// 合并输出
			template.process(hashMap, new OutputStreamWriter(
					new FileOutputStream(htmlFile), "utf-8"));

		}
		ServletActionContext.getResponse().setContentType(
				"text/html;charset=utf-8");
		FileUtils.copyFile(htmlFile, ServletActionContext.getResponse()
				.getOutputStream());
		return NONE;
	}

}
